/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.manager.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConstants;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.defipay.api.client.domain.response.CreateOrderResponse;
import com.defipay.api.client.impl.LocalSigner;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayAppOrderResult;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.order.WxPayMwebOrderResult;
import com.github.binarywang.wxpay.bean.order.WxPayNativeOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.google.common.base.Throwables;
import com.paypal.orders.OrdersCreateRequest;
import com.yami.shop.bean.app.param.PayInfoParam;
import com.yami.shop.bean.bo.PayInfoResultBO;
import com.yami.shop.bean.bo.RefundInfoBo;
import com.yami.shop.bean.enums.BackType;
import com.yami.shop.bean.enums.PayStatus;
import com.yami.shop.bean.event.BalancePayEvent;
import com.yami.shop.bean.event.BalanceRefundEvent;
import com.yami.shop.bean.model.PayInfo;
import com.yami.shop.bean.param.PayPalOrderParam;
import com.yami.shop.bean.param.WebhookParam;
import com.yami.shop.bean.pay.PayInfoDto;
import com.yami.shop.bean.pay.RefundInfoDto;
import com.yami.shop.common.bean.Domain;
import com.yami.shop.common.bean.FaTPay;
import com.yami.shop.common.bean.FaTPayEnv;
import com.yami.shop.common.bean.SysPayConfig;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.enums.PayType;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.IPHelper;
import com.yami.shop.common.util.Json;
import com.yami.shop.config.AliPayConfig;
import com.yami.shop.config.FaTPayConfig;
import com.yami.shop.config.PayPalConfig;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.config.WxConfig;
import com.yami.shop.dao.PayInfoMapper;
import com.yami.shop.service.SysConfigService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 统一支付工具
 *
 * @author LGH
 */
@Service
@AllArgsConstructor
public class PayManager {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AliPayConfig aliPayConfig;

    @Autowired
    private ShopConfig shopConfig;

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private PayPalConfig payPalConfig;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private PayInfoMapper payInfoMapper;

    @Autowired
    private FaTPayConfig faTPayConfig;

    private static final String WX_SUCCESS_XML = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    private static final String ALI_SUCCESS = "success";
    private static final String SUCCESS = "SUCCESS";
    private static final String TRADE_STATUS = "trade_status";
    private static final String TRADE_SUCCESS = "TRADE_SUCCESS";
    private static final String REFUND_FEE = "refund_fee";
    private static final String TRADE_CLOSED = "TRADE_CLOSED";

    public ServerResponseEntity<?> doPay(HttpServletResponse httpResponse, PayInfoDto payInfo) throws WxPayException, AlipayApiException {
        if (payInfo.getPayAmount() < Constant.MIN_PRODUCT_AMOUNT && Objects.equals(payInfo.getPayType(), PayType.SCOREPAY.value())) {
            return ServerResponseEntity.success();
        }
        // 微信支付不能大于1000w
        if (payInfo.getPayAmount() < Constant.MIN_PRODUCT_AMOUNT || payInfo.getPayAmount() > Constant.WECHAT_MAX_PAY_AMOUNT) {
            // 订单金额有误，无法进行支付
            throw new YamiShopBindException("yami.order.amount.error");
        }
        SysPayConfig sysPayConfig = sysConfigService.getSysConfigObject(Constant.PAY_SWITCH_CONFIG, SysPayConfig.class);
        String domainName = shopConfig.getDomain().getApiDomainName();
        // 如果是商家端需要回调，则使用商家端的地址
        if (Objects.nonNull(payInfo.getBackType()) && Objects.equals(payInfo.getBackType(), BackType.SHOP.value())) {
            domainName = shopConfig.getDomain().getMultishopDomainName();
        }
        String notifyUrl = domainName + payInfo.getApiNoticeUrl();

        PayType payType = PayType.instance(payInfo.getPayType());
        if (PayType.isWxPay(payType)) {
            return doWxPay(payInfo, sysPayConfig, notifyUrl, payType);
        } else if (Objects.equals(payType, PayType.ALIPAY)) {
            if (!sysPayConfig.getAliPaySwitch()) {
                throw new YamiShopBindException("yami.order.pay.type.check");
            }
            //创建API对应的request
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();

            //在公共参数中设置回跳和通知地址
            alipayRequest.setNotifyUrl(notifyUrl);
            alipayRequest.setReturnUrl(payInfo.getReturnUrl());
            AlipayTradePagePayModel alipayTradePagePayModel = new AlipayTradePagePayModel();
            alipayTradePagePayModel.setOutTradeNo(payInfo.getPayNo());
            alipayTradePagePayModel.setBody(payInfo.getBody());
            alipayTradePagePayModel.setSubject(payInfo.getBody());
            alipayTradePagePayModel.setTotalAmount(Double.toString(payInfo.getPayAmount()));
            alipayTradePagePayModel.setProductCode("FAST_INSTANT_TRADE_PAY");
            alipayRequest.setBizModel(alipayTradePagePayModel);

            return ServerResponseEntity.success(aliPayConfig.getAlipayClient().pageExecute(alipayRequest).getBody());
        } else if (Objects.equals(payType, PayType.ALIPAY_H5)) {
            if (!sysPayConfig.getAliPaySwitch()) {
                throw new YamiShopBindException("yami.order.pay.type.check");
            }
            AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
            alipayRequest.setNotifyUrl(notifyUrl);
            alipayRequest.setReturnUrl(payInfo.getReturnUrl());

            AlipayTradeWapPayModel alipayTradeWapPayModel = new AlipayTradeWapPayModel();
            alipayTradeWapPayModel.setOutTradeNo(payInfo.getPayNo());
            alipayTradeWapPayModel.setSubject(payInfo.getBody());
            alipayTradeWapPayModel.setTotalAmount(Double.toString(payInfo.getPayAmount()));
            alipayTradeWapPayModel.setProductCode("QUICK_WAP_PAY");
            alipayRequest.setBizModel(alipayTradeWapPayModel);
            return ServerResponseEntity.success(aliPayConfig.getAlipayClient().pageExecute(alipayRequest).getBody());
        }
        // 支付宝app支付
        else if (Objects.equals(payType, PayType.ALIPAY_APP)) {
            if (!sysPayConfig.getAliPaySwitch()) {
                throw new YamiShopBindException("yami.order.pay.type.check");
            }
            AlipayTradeAppPayRequest alipayRequest = new AlipayTradeAppPayRequest();
            alipayRequest.setNotifyUrl(notifyUrl);
            AlipayTradeAppPayModel alipayTradeAppPayModel = new AlipayTradeAppPayModel();
            alipayTradeAppPayModel.setOutTradeNo(payInfo.getPayNo());
            alipayTradeAppPayModel.setSubject(payInfo.getBody());
            alipayTradeAppPayModel.setTotalAmount(Double.toString(payInfo.getPayAmount()));
            alipayTradeAppPayModel.setProductCode("QUICK_MSECURITY_PAY");
            alipayRequest.setBizModel(alipayTradeAppPayModel);

            String body = aliPayConfig.getAlipayClient().sdkExecute(alipayRequest).getBody();
            return ServerResponseEntity.success(body);
        }
        //余额支付
        else if (Objects.equals(payType, PayType.BALANCE)) {
            if (!sysPayConfig.getBalancePaySwitch()) {
                throw new YamiShopBindException("yami.order.pay.type.check");
            }
            PayInfoParam payInfoParam = new PayInfoParam();
            applicationContext.publishEvent(new BalancePayEvent(payInfo, payInfoParam));
            return ServerResponseEntity.success(payInfoParam);
        }
        //PayPal支付
        else if (Objects.equals(payType, PayType.PAYPAL)) {

            return doPayPalPay(payInfo, sysPayConfig, notifyUrl);
            //FaTPay支付
        }else if(Objects.equals(payType,PayType.FATPAY)){
            return doPayFaTPay(payInfo,sysPayConfig,notifyUrl);
        }
        // 一般是积分支付才会到这一步
        return ServerResponseEntity.success();
    }

    /**
     * FaTPay支付
     * @param payInfoDto
     * @param sysPayConfig
     * @param notifyUrl
     * @return
     */
    private ServerResponseEntity<String> doPayFaTPay(PayInfoDto payInfoDto, SysPayConfig sysPayConfig, String notifyUrl){
       if(!sysPayConfig.getFatPaySwitch()){
           throw new YamiShopBindException("yami.order.pay.type.check");
       }
       payInfoDto.setApiNoticeUrl(notifyUrl);
       CreateOrderResponse response = faTPayConfig.createOrder(payInfoDto);
       PayInfo payInfo = payInfoMapper.selectOne(new LambdaQueryWrapper<PayInfo>().eq(PayInfo::getPayNo, payInfoDto.getPayNo()));
       payInfo.setBizPayNo(response.getTransNo());
       int updateCount = payInfoMapper.update(payInfo, Wrappers.lambdaUpdate(PayInfo.class)
            .eq(PayInfo::getPayNo, payInfoDto.getPayNo()));
       if (updateCount < 1) {
            // 支付信息更新失败
           throw new YamiShopBindException("yami.shop.pay.info.update.error");
        }
       return ServerResponseEntity.success(JSONUtil.toJsonStr(response));
    }

    private ServerResponseEntity<String> doPayPalPay(PayInfoDto payInfoDto, SysPayConfig sysPayConfig, String notifyUrl) {
        if (!sysPayConfig.getPayPalSwitch()) {
            throw new YamiShopBindException("yami.order.pay.type.check");
        }
        payInfoDto.setApiNoticeUrl(notifyUrl);
        OrdersCreateRequest request = payPalConfig.createPayPalOrder(payInfoDto);
        PayPalOrderParam param = payPalConfig.getExcetuteHref(request);
        // 根据支付单号，更新第三方订单号
        PayInfo payInfo = payInfoMapper.selectOne(new LambdaQueryWrapper<PayInfo>().eq(PayInfo::getPayNo, payInfoDto.getPayNo()));
        payInfo.setBizOrderNo(param.getOrderId());
        int updateCount = payInfoMapper.update(payInfo, Wrappers.lambdaUpdate(PayInfo.class)
                .eq(PayInfo::getPayNo, payInfoDto.getPayNo()));
        if (updateCount < 1) {
            // 支付信息更新失败
            throw new YamiShopBindException("yami.shop.pay.info.update.error");
        }
        // 创建钩子，如果已经在paypal配置好钩子可以将下面一行注释掉
        payPalConfig.createWebhook(payInfoDto.getApiNoticeUrl());
        return ServerResponseEntity.success(param.getHref());
    }

    private ServerResponseEntity<?> doWxPay(PayInfoDto payInfo, SysPayConfig sysPayConfig, String notifyUrl, PayType payType) throws WxPayException {
        if (!sysPayConfig.getWxPaySwitch()) {
            throw new YamiShopBindException("yami.order.pay.type.check");
        }
        WxPayService wxPayService = wxConfig.getWxPayService(payType);
        WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
        orderRequest.setBody(payInfo.getBody());
        orderRequest.setOutTradeNo(payInfo.getPayNo());
        orderRequest.setTotalFee((int) Arith.mul(payInfo.getPayAmount(), 100));
        orderRequest.setSpbillCreateIp(IPHelper.getIpAddr());
        orderRequest.setOpenid(payInfo.getBizUserId());
        orderRequest.setNotifyUrl(notifyUrl);

        // 微信小程序支付 || 微信公众号支付
        if (Objects.equals(payType, PayType.WECHATPAY) || Objects.equals(payType, PayType.WECHATPAY_MP)) {
            orderRequest.setTradeType(WxPayConstants.TradeType.JSAPI);
            WxPayMpOrderResult wxPayMpOrderResult = wxPayService.createOrder(orderRequest);
            return ServerResponseEntity.success(wxPayMpOrderResult);
        }
        // 微信网页支付
        else if (Objects.equals(payType, PayType.WECHATPAY_SWEEP_CODE)) {
            orderRequest.setProductId(payInfo.getPayNo());
            // 生成微信二维码
            orderRequest.setTradeType(WxPayConstants.TradeType.NATIVE);
            WxPayNativeOrderResult wxPayNativeOrderResult = wxPayService.createOrder(orderRequest);

            return ServerResponseEntity.success(wxPayNativeOrderResult.getCodeUrl());
        }
        // 微信H5支付
        else if (Objects.equals(payType, PayType.WECHATPAY_H5)) {
            // 生成微信二维码
            orderRequest.setTradeType(WxPayConstants.TradeType.MWEB);
            String s = "{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"\",\"wap_name\": \"\"}}";
            orderRequest.setSceneInfo(s);
            WxPayMwebOrderResult wxPayMwebOrderResult = wxPayService.createOrder(orderRequest);
            return ServerResponseEntity.success(wxPayMwebOrderResult.getMwebUrl());
        }
        // 微信app支付
        else if (Objects.equals(payType, PayType.WECHATPAY_APP)) {
            orderRequest.setTradeType(WxPayConstants.TradeType.APP);
            WxPayAppOrderResult wxPayAppOrderResult = wxPayService.createOrder(orderRequest);
            return ServerResponseEntity.success(wxPayAppOrderResult);
        }
        return null;
    }

    /**
     * 校验支付结果，并返回支付单号
     */
    public PayInfoResultBO validateAndGetPayInfo(HttpServletRequest request, PayType payType, String xmlData) throws UnsupportedEncodingException, WxPayException, AlipayApiException {

        PayInfoResultBO payInfoResultBO = new PayInfoResultBO();

        if (PayType.isWxPay(payType)) {
            WxPayService wxPayService = wxConfig.getWxPayService(payType);
            WxPayOrderNotifyResult parseOrderNotifyResult = wxPayService.parseOrderNotifyResult(xmlData);
            payInfoResultBO.setPayNo(parseOrderNotifyResult.getOutTradeNo());
            payInfoResultBO.setBizPayNo(parseOrderNotifyResult.getTransactionId());
            payInfoResultBO.setIsPaySuccess(SUCCESS.equals(parseOrderNotifyResult.getResultCode()));
            payInfoResultBO.setSuccessString(WX_SUCCESS_XML);
            payInfoResultBO.setPayAmount(Arith.div(parseOrderNotifyResult.getTotalFee(), 100));
            payInfoResultBO.setCallbackContent(xmlData);

        } else if (PayType.isAliPay(payType)) {
            //获取支付宝POST过来反馈信息
            Map<String, String> params = parseAliNotifyAndGetResult(request);

            if (Objects.equals(params.get(TRADE_STATUS), TRADE_SUCCESS)) {
                //商户订单号,之前生成的带用户ID的订单号
                payInfoResultBO.setPayNo(params.get("out_trade_no"));
                //支付宝交易号
                payInfoResultBO.setBizPayNo(params.get("trade_no"));
                payInfoResultBO.setIsPaySuccess(true);
                payInfoResultBO.setSuccessString(ALI_SUCCESS);
                payInfoResultBO.setPayAmount(new BigDecimal(params.get("total_amount")).doubleValue());
                // 这个是支付宝退款的通知
                if (StrUtil.isNotBlank(params.get(REFUND_FEE))) {
                    payInfoResultBO.setIsPaySuccess(false);
                }
            } else {
                payInfoResultBO.setIsPaySuccess(false);
            }
            payInfoResultBO.setCallbackContent(Json.toJsonString(params));

        } else if (Objects.equals(payType, PayType.PAYPAL)) {
            // webhook 回调
            Map<String, String> headers = payPalConfig.getHeadersInfo(request);
            WebhookParam webhookParam = JSON.parseObject(xmlData, WebhookParam.class);
            boolean isVerify = payPalConfig.verifyWebhookSign(request, headers, xmlData);
            if (!isVerify) {
                // 验签失败
                throw new YamiShopBindException("yami.sign.check");
            }
            String bizOrderNo = webhookParam.getResource().getId();
            if (StrUtil.isNotBlank(bizOrderNo)) {
                // 查询是否支付完成如果系统订单是已经支付完成就退款
                PayInfo payInfo = payInfoMapper.selectOne(Wrappers.lambdaQuery(PayInfo.class)
                        .eq(PayInfo::getBizOrderNo, bizOrderNo).last("limit 1"));
                if (Objects.isNull(payInfo)) {
                    // 找不到支付记录
                    throw new YamiShopBindException("找不到支付记录" + xmlData);
                }
                if (Objects.equals(PayStatus.PAYED.value(), payInfo.getPayStatus())) {
                    // 已支付完成,支付失败，订单不在未支付状态
                    throw new YamiShopBindException("yami.order.pay.fail");
                }
                // 执行扣款操作
                payInfoResultBO = payPalConfig.captureOrder(bizOrderNo);
            } else {
                payInfoResultBO.setIsPaySuccess(false);
            }
            payInfoResultBO.setCallbackContent(xmlData);
        }else if(Objects.equals(payType,PayType.FATPAY)){
            String timestamp = request.getHeader("BIZ_TIMESTAMP");
            String signature = request.getHeader("BIZ_RESP_SIGNATURE");
            boolean verifyResult = false;
            try{
                FaTPayEnv faTPay = shopConfig.getFaTPay();
                if (!StringUtils.isEmpty(timestamp) && !StringUtils.isEmpty(signature)) {
                    String body = xmlData;
                    String content = body + "|" + timestamp;
                    verifyResult = LocalSigner.verifyEcdsaSignature(content, signature, faTPay.getPublicKey());
                }
            }catch(Exception e){
                logger.error("FaTPay支付回调失败，失败原因：{}", Throwables.getStackTraceAsString(e));
                throw new YamiShopBindException("yami.sign.check");
            }
            if(verifyResult){
                JSONObject jsonObject=JSONUtil.parseObj(xmlData);
                if(jsonObject.containsKey("state") && jsonObject.getInt("state").equals(200)){
                    //成功
                    Integer type=jsonObject.getInt("type");
                    if(type==1){
                        String payNo=jsonObject.getStr("memberTransNo");
                        payInfoResultBO.setIsPaySuccess(true);
                        payInfoResultBO.setBizPayNo(jsonObject.getStr("transNo"));
                        payInfoResultBO.setSuccessString(ALI_SUCCESS);
                        payInfoResultBO.setPayAmount(Double.parseDouble(jsonObject.getStr("realOriginAmount")));
                        payInfoResultBO.setPayNo(payNo);
                    }else{
                        payInfoResultBO.setIsPaySuccess(false);
                    }
                }else{
                    payInfoResultBO.setIsPaySuccess(false);
                }
                payInfoResultBO.setCallbackContent(xmlData);
            }else{
                throw new YamiShopBindException("yami.sign.check");
            }
        }

        if (StrUtil.isNotBlank(payInfoResultBO.getCallbackContent())) {
            PayInfo payInfo = new PayInfo();
            payInfo.setPayNo(payInfoResultBO.getPayNo());
            payInfo.setBizPayNo(payInfoResultBO.getBizPayNo());
            payInfo.setBizOrderNo(payInfoResultBO.getBizOrderNo());
            payInfo.setCallbackTime(new Date());
            payInfo.setCallbackContent(payInfoResultBO.getCallbackContent());
            payInfoMapper.update(payInfo, new LambdaUpdateWrapper<PayInfo>().eq(PayInfo::getPayNo, payInfo.getPayNo()));
        }
        return payInfoResultBO;
    }

    public boolean doRefund(RefundInfoDto refundInfo) {

        PayType payType = refundInfo.getPayType();
        if (Objects.equals(refundInfo.getRefundAmount(), 0.0)) {
            return true;
        }
        Domain domain = shopConfig.getDomain();
        // 提交提款操作
        try {
            if (PayType.isWxPay(payType)) {
                // 退款操作
                // 生成退款请求对象
                WxPayRefundRequest wxPayRefundRequest = new WxPayRefundRequest();
                // 商户订单号
                wxPayRefundRequest.setOutTradeNo(refundInfo.getPayNo());
                // 订单金额
                double totalFee = Arith.mul(refundInfo.getPayAmount(), 100);
                wxPayRefundRequest.setTotalFee((int) totalFee);
                // 退款金额
                double refundFee = Arith.mul(refundInfo.getRefundAmount(), 100);
                wxPayRefundRequest.setRefundFee((int) refundFee);
                // 退款编码
                wxPayRefundRequest.setOutRefundNo(refundInfo.getRefundSn());

                // notifyUrl（通知结果）
                if (!Objects.equals(refundInfo.getOnlyRefund(), 1)) {
                    // 只进行退款，不需要任何回调
                    wxPayRefundRequest.setNotifyUrl(domain.getMultishopDomainName() + refundInfo.getNotifyUrl());
                }
                WxPayService wxPayService = wxConfig.getWxPayService(payType);
                wxPayService.refund(wxPayRefundRequest);

            } else if (PayType.isAliPay(payType)) {
                AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
                request.setNotifyUrl(domain.getMultishopDomainName() + refundInfo.getNotifyUrl());
                AlipayTradeRefundModel alipayTradeRefundModel = new AlipayTradeRefundModel();
                alipayTradeRefundModel.setOutTradeNo(refundInfo.getPayNo());
                alipayTradeRefundModel.setOutRequestNo(refundInfo.getRefundSn());
                alipayTradeRefundModel.setRefundAmount(Double.toString(refundInfo.getRefundAmount()));
                request.setBizModel(alipayTradeRefundModel);
                AlipayTradeRefundResponse response = aliPayConfig.getAlipayClient().certificateExecute(request);
                // 对fund_change必须了解为本次退款操作，若相同退款参数调用，第一次返回fund_change=Y，第二次返回fund_change=N，但是第二次仍返回退款信息。
                if (response.isSuccess() && StrUtil.isNotBlank(response.getFundChange())) {
                    return true;
                }
            } else if (Objects.equals(payType, PayType.BALANCE)) {
                applicationContext.publishEvent(new BalanceRefundEvent(refundInfo));
            } else if (Objects.equals(payType, PayType.PAYPAL)) {
                // payPal申请退款
                return payPalConfig.refundOrder(refundInfo);
            }
        } catch (WxPayException e) {
            logger.error("微信退款发生错误：", e);
            throw new YamiShopBindException(e.getCustomErrorMsg(), e);
        } catch (AlipayApiException e) {
            logger.error("阿里退款发生错误：", e);
            throw new YamiShopBindException(e.getErrMsg(), e);
        }
        return false;
    }

    public RefundInfoBo validateAndGetRefundInfo(HttpServletRequest request, PayType payType, String xmlData) throws UnsupportedEncodingException, WxPayException, AlipayApiException {

        RefundInfoBo refundInfoBo = new RefundInfoBo();
        refundInfoBo.setIsRefundSuccess(false);

        if (PayType.isWxPay(payType)) {
            WxPayRefundNotifyResult wxPayRefundNotifyResult = wxConfig.getWxPayService(payType).parseRefundNotifyResult(xmlData);
            WxPayRefundNotifyResult.ReqInfo reqInfo = wxPayRefundNotifyResult.getReqInfo();
            if (Constant.SUCCESS.equals(reqInfo.getRefundStatus())) {
                refundInfoBo.setIsRefundSuccess(true);
                refundInfoBo.setSuccessString(WX_SUCCESS_XML);
                refundInfoBo.setRefundNo(reqInfo.getOutRefundNo());
                refundInfoBo.setBizRefundNo(reqInfo.getRefundId());
                refundInfoBo.setCallbackContent(xmlData);
            }
        } else if (PayType.isAliPay(payType)) {
            Map<String, String> params = parseAliNotifyAndGetResult(request);
            if (Objects.equals(params.get(TRADE_STATUS), TRADE_SUCCESS) || Objects.equals(params.get(TRADE_STATUS), TRADE_CLOSED)) {
                refundInfoBo.setIsRefundSuccess(true);
                refundInfoBo.setRefundNo(params.get("out_biz_no"));
                refundInfoBo.setBizRefundNo("");
                refundInfoBo.setSuccessString(ALI_SUCCESS);
                refundInfoBo.setCallbackContent(Json.toJsonString(params));
            }
        }
        return refundInfoBo;
    }

    public PayInfoResultBO getPayInfo(PayType payType, String payNo, String bizPayNo) {
        PayInfoResultBO payInfo = new PayInfoResultBO();
        payInfo.setPayNo(payNo);
        payInfo.setBizPayNo(bizPayNo);
        try {
            if (PayType.isWxPay(payType)) {
                WxPayService wxPayService = wxConfig.getWxPayService(payType);
                WxPayOrderQueryResult wxPayOrderQueryResult = wxPayService.queryOrder(null, payNo);
                if (!Objects.isNull(wxPayOrderQueryResult) && Objects.equals(wxPayOrderQueryResult.getTradeState(), Constant.SUCCESS)) {
                    payInfo.setBizPayNo(wxPayOrderQueryResult.getTransactionId());
                    payInfo.setIsPaySuccess(true);
                } else {
                    payInfo.setIsPaySuccess(false);
                }
            } else if (PayType.isAliPay(payType)) {
                AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
                AlipayTradeQueryModel alipayTradeQueryModel = new AlipayTradeQueryModel();
                alipayTradeQueryModel.setOutTradeNo(payNo);

                request.setBizModel(alipayTradeQueryModel);
                AlipayTradeQueryResponse response = aliPayConfig.getAlipayClient().execute(request);
                if (response.isSuccess()) {
                    payInfo.setBizPayNo(response.getTradeNo());
                    payInfo.setIsPaySuccess(true);
                } else {
                    payInfo.setIsPaySuccess(false);
                }
            } else if (Objects.equals(payType, PayType.PAYPAL)) {
                // paypal查单
                if (Objects.isNull(bizPayNo)) {
                    payInfo.setIsPaySuccess(false);
                    return payInfo;
                }
                payPalConfig.getCapture(payInfo);
            } else {
                payInfo.setIsPaySuccess(false);
            }
        } catch (WxPayException | AlipayApiException e) {
            logger.error("获取支付信息错误：", e);
            payInfo.setIsPaySuccess(false);
        }
        return payInfo;
    }

    public Boolean cancelOrderQrCode(List<PayInfo> payInfoList) throws WxPayException, AlipayApiException {
        Map<Integer, List<PayInfo>> payTypeMap = payInfoList.stream().collect(Collectors.groupingBy(PayInfo::getPayType));
        for (Integer payType : payTypeMap.keySet()) {
            PayType type = PayType.instance(payType);
            List<PayInfo> infoList = payTypeMap.get(payType);
            for (PayInfo payInfo : infoList) {
                if (PayType.isWxPay(type)) {
                    WxPayService wxPayService = wxConfig.getWxPayService(type);
                    wxPayService.closeOrder(payInfo.getPayNo());
                } else if (PayType.isAliPay(type)) {
                    AlipayTradeCloseRequest tradeCloseRequest = new AlipayTradeCloseRequest();
                    AlipayTradeCloseModel tradeCloseModel = new AlipayTradeCloseModel();
                    tradeCloseModel.setOutTradeNo(payInfo.getPayNo());
                    tradeCloseRequest.setBizModel(tradeCloseModel);
                    AlipayTradeCloseResponse response = aliPayConfig.getAlipayClient().execute(tradeCloseRequest);
                    logger.warn(response.getBody());
                    if (!response.isSuccess()) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * 获取支付宝POST过来反馈信息
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws AlipayApiException
     */
    private Map<String, String> parseAliNotifyAndGetResult(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        Map<String, String> params = getRequestParamsMap(request);
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCertCheckV1(params, shopConfig.getAlipay().getAlipayCertPath(), cn.hutool.core.util.CharsetUtil.UTF_8, AlipayConstants.SIGN_TYPE_RSA2);

        if (!signVerified) {
            // 验签失败
            throw new YamiShopBindException("yami.sign.check");
        }
        return params;
    }

    /**
     * 获取请求参数
     */
    private Map<String, String> getRequestParamsMap(HttpServletRequest request) throws UnsupportedEncodingException {
        //乱码解决，这段代码在出现乱码时使用
        request.setCharacterEncoding("utf-8");
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>(16);
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        return params;
    }
}
